package com.kuqi.service.impl;

import com.kuqi.domain.UserAvatar;
import com.kuqi.mapper.FilesMapper;
import com.kuqi.mapper.UserMapper;
import com.kuqi.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:kuqi
 * @createTime:2021/11/14 18:01
 * @description:
 */
@Service
public class FilesServiceImpl implements FilesService {

    @Autowired
    private FilesMapper filesMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 上传的同时不仅要把当前图片的地址存放到avatar表中，还有把user表中的avatar中的id给user表中的avatarid
     * @param userAvatar
     */
    @Override
    public void saveAvatar(UserAvatar userAvatar) {
        //1.存avatar信息
        filesMapper.saveAvatar(userAvatar);
        //2.此时的userAvatar中只有avatarUr和用户id根据这个来查其Avatarid
        Integer avatarId = filesMapper.getAvatarId(userAvatar);

        /**
         * 因为这里前面两步id是数据库中自动生成的，所以先存储avatar的地址和用户id到avatar表中
         * 然后再到表中取出avatar表生成的id主键，没有封装到同一个对象中，所以下面进行封装。
         */
        Map<Object,Object> map = new HashMap<>();
        map.put("id",userAvatar.getUserid());
        map.put("avatarid",avatarId);

        //回到user表中将对应的avatar添加上去
        userMapper.setAvatarId(map);
    }

    /**
     *
     * @param id--->此时的id为userid，先根据userid查avatarid
     * @return
     */
    @Override
    public UserAvatar getAvatar(Integer id) {
        /*查询user表中的用户对应的avatarid*/
        Integer avatarId = userMapper.getAvatarIdByUserId(id);
        /*根据avatarid去avatar表中查询该信息*/
        return filesMapper.getAvatar(avatarId);
    }
}
